﻿package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.net.*;
    import flash.display.*;
    import flash.events.*;
    import flash.utils.ByteArray;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
    public class uploadImage extends Sprite 
	{
        private var jagFileRefSave:FileReference = new FileReference();
        private var loader:Loader = new Loader();
		private var imagesFilter:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
		private var textFilter:FileFilter = new FileFilter("Text Files (*.php,*.xml)", "*.php; *.xml");
		private var imgContainer:ImgContainer;
		private var allTypes:Array;
		private var UrlRequest:URLRequest;

    public function uploadImage()
	{
        super();
		allTypes = new Array(imagesFilter, textFilter);
		UrlRequest = new URLRequest("uploader_script.php");
        //upload_Image.addEventListener(MouseEvent.CLICK,onClickSave);
		UploadButton.addEventListener(MouseEvent.CLICK,onClickSave);
		//upload_btn.addEventListener(MouseEvent.CLICK, uploadVars);
		//jagFileRefSave.addEventListener(ProgressEvent.PROGRESS, progressHandler);
	}
    public function onClickSave(e:MouseEvent):void{
		file_name.text = "";
		file_size.text = "";
		if(getChildByName("imgContainer") != null)
		{
			removeChild(getChildByName("imgContainer"));
		}
        jagFileRefSave.browse(allTypes);
        jagFileRefSave.addEventListener(Event.SELECT, selectedFile);
    }
    public function selectedFile(e:Event):void
	{
		fileDisplay_txt.text = jagFileRefSave.name;
		jagFileRefSave.load();
		if((jagFileRefSave.type == ".php") ||  (jagFileRefSave.type == ".xml"))
		{
			file_name.text = "Selected file name is : "+jagFileRefSave.name;
			file_size.text = "Selected file size is : "+(jagFileRefSave.size/1024)+" KB";
		}
		else
		{
	      	jagFileRefSave.addEventListener(Event.COMPLETE, loaded);
		}
    }
	private function uploadVars(e:MouseEvent):void
	{
		if(fileDisplay_txt.text != "")
		{
			jagFileRefSave.upload(UrlRequest);
			status_txt.text = jagFileRefSave.name + " has been uploaded.";
			fileDisplay_txt.text = "";
		}
	}
    private function loaded(e:Event):void{
        var rawBytes:ByteArray = jagFileRefSave.data;
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, getBitmapData)
        loader.loadBytes(rawBytes);
    }
    private function getBitmapData(e:Event):void
	{
		imgContainer = new ImgContainer();
		imgContainer.name = "imgContainer";
        imgContainer.addChild(loader);
		imgContainer.width = 150;
		imgContainer.height = 150;
		imgContainer.x = stage.stageWidth/2 - imgContainer.width/2;
		imgContainer.y = stage.stageHeight/4;
		addChild(imgContainer);
    }

    }
}
